/*
 * Copyright 2011-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.jmh.benchmark;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Logging Benchmark.
 *
 * @author liym
 * @since 2020-05-26 10:50 新建
 */
@State(Scope.Thread)
public class LoggingBenchmark {

    private static final int COUNT = 100;

    private Logger logger;

    @Setup
    public void setup() {
        this.logger = LoggerFactory.getLogger(this.getClass());
    }

    @Benchmark
    public void testConcatenatingStrings() {
        String x = "", y = "", z = "";

        for (int i = 0; i < COUNT; i++) {
            x += i;
            y += i;
            z += i;

            this.logger.debug("Concatenating strings: " + x + y + z);
        }
    }

    @Benchmark
    public void testVariableArguments() {
        String x = "", y = "", z = "";

        for (int i = 0; i < COUNT; i++) {
            x += i;
            y += i;
            z += i;

            this.logger.debug("Variable arguments: {} {} {}", x, y, z);
        }
    }

    @Benchmark
    public void testIfDebugEnabled() {
        String x = "", y = "", z = "";

        for (int i = 0; i < COUNT; i++) {
            x += i;
            y += i;
            z += i;

            if (this.logger.isDebugEnabled()) {
                this.logger.debug("If debug enabled: {} {} {}", x, y, z);
            }
        }
    }

    public static void main(String[] args) throws RunnerException {
        Options options = new OptionsBuilder()
                .include(LoggingBenchmark.class.getName())
                // .include(LoggingBenchmark.class.getName() + ".*testIfDebugEnabled*")
                .warmupIterations(5)
                .measurementIterations(5)
                .forks(1)
                .build();

        new Runner(options).run();
    }

}
